<?php

class FlatController extends Controller
{


    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
                'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($blockId)
    {

        $block = $this->loadBlock($blockId);
        $this->accessDeniedIf(!checkAccess('ownBlock', array('block'=>$block)));

        $model=new Flat;

        $model->block = $block;

        if(isset($_POST['Flat']))
        {
            $model->attributes=$_POST['Flat'];
            $model->block = $block;

            if($model->save()){
                $this->redirect(array('index','blockId'=>$blockId));
            }
        }

        $this->render('create',array(
                'model'=>$model,
                'block'=>$block
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        $this->accessDeniedIf(!checkAccess('ownBlock', array('block'=>$model->block)));

        $block = $model->block;

        if(isset($_POST['Flat']))
        {
            $model->attributes=$_POST['Flat'];
            $model->block = $block;

            if($model->save()){
                $this->redirect(array('flat/index','blockId'=>$block->id));
            }
        }

        $this->render('update',array(
                'model'=>$model,
                'block'=>$model->block
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
            $model = $this->loadModel($id);

            $this->accessDeniedIf(!checkAccess('ownBlock', array('block'=>$model->block)));

            $model->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));

    }

    /**
     * Lists all models.
     */
    /**
     * Lists all models.
     */
    public function actionIndex($blockId = null)
    {

        if(null == $blockId){
            $block = Block::model()->owned(user()->id)->find();
        }else{
            $block = $this->loadBlock($blockId);
        }

        if(null != $block){
             $this->accessDeniedIf(!checkAccess('ownBlock', array('block'=>$block)), 'Nincs joga ehhez a háztömbhöz.');
        }

        $model=new Flat('search');
        $model= $model->byBlock($block);

        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Flat'])){
            $model->attributes=$_GET['Flat'];
        }

        $blocks = array();
        if(checkAccess('admin')){

            foreach (User::model()->findAll() as $user){

                $userBlocks = Block::model()->owned($user)->findAll();

                $blocks[$user->username] = CHtml::listData($userBlocks, 'id', 'name');

            }


        }else{
            $blocks = Block::model()->owned(user()->id)->findAll();
            $blocks = CHtml::listData($blocks, 'id', 'name');
        }

        $this->render('index',array(
                'model'=>$model,
                'blocks'=>$blocks,
                'block'=>$block
        ));
    }



    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Flat::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    protected function loadBlock($id)
    {
        $model=Block::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'A megadott háztömb nem létezik.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='flat-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionGenerateExcel()
    {
        $session=new CHttpSession;
        $session->open();

        if(isset($session['Flat_records']))
        {
            $model=$session['Flat_records'];
        }
        else
            $model = Flat::model()->findAll();


        Yii::app()->request->sendFile(date('YmdHis').'.xls',
        $this->renderPartial('excelReport', array(
        'model'=>$model
        ), true)
        );
    }
    public function actionGeneratePdf()
    {
        $session=new CHttpSession;
        $session->open();
        Yii::import('application.extensions.giiplus.bootstrap.*');
        require_once('tcpdf/tcpdf.php');
        require_once('tcpdf/config/lang/eng.php');

        if(isset($session['Flat_records']))
        {
            $model=$session['Flat_records'];
        }
        else
            $model = Flat::model()->findAll();



        $html = $this->renderPartial('expenseGridtoReport', array(
                'model'=>$model
        ), true);

        //die($html);

        $pdf = new TCPDF();
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor(Yii::app()->name);
        $pdf->SetTitle('Flat Report');
        $pdf->SetSubject('Flat Report');
        //$pdf->SetKeywords('example, text, report');
        $pdf->SetHeaderData('', 0, "Report", '');
        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, "Example Report by ".Yii::app()->name, "");
        $pdf->setHeaderFont(Array('helvetica', '', 8));
        $pdf->setFooterFont(Array('helvetica', '', 6));
        $pdf->SetMargins(15, 18, 15);
        $pdf->SetHeaderMargin(5);
        $pdf->SetFooterMargin(10);
        $pdf->SetAutoPageBreak(TRUE, 0);
        $pdf->SetFont('dejavusans', '', 7);
        $pdf->AddPage();
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->LastPage();
        $pdf->Output("Flat_002.pdf", "I");
    }
}
